package ui.gui.documents;

import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;


public class EditorFactory {
	
	private HashMap<String, AbstractDocument> _types = new HashMap<String, AbstractDocument>();
	private AbstractDocument _defaultEditor = null;
	private static EditorFactory _instance = null;
	private EditorFactory() {
		
	}
	public static void Prepare() {
		getInstance().register(new AltaricaCodeEditor());
		getInstance().register(new PlainTextEditor());
		getInstance().registerDefaultEditor(new PlainTextEditor());
	}
	
	public static EditorFactory getInstance() {
		if (_instance == null) _instance = new EditorFactory();
		return _instance;
	}
	
	public Collection<AbstractDocument> getRegisteredEditors() {
		return Collections.unmodifiableCollection(_types.values());
	}

	public void registerDefaultEditor(AbstractDocument doc) {
		this._defaultEditor = doc;
	}
	public void register(AbstractDocument document) {
		if (!_types.containsKey(document.getExtension())) {
			_types.put(document.getExtension(), document);
		}
	}
	
	public AbstractDocument createFromFile(File file) {
		String extension = file.getName();
		extension = extension.substring(extension.lastIndexOf('.'));
		if (_types.containsKey(extension)) {
			AbstractDocument document = _types.get(extension);
			
			AbstractDocument newInstance = (AbstractDocument)document.clone();
			newInstance.setFile(file);
			return newInstance;
		}
		AbstractDocument defaultEditor = (AbstractDocument)_defaultEditor.clone();
		defaultEditor.setFile(file);
		return defaultEditor;
	}
	
	public String [] getExtensionFilter() {
		String []filter = new String[_types.values().size()];
		int i = 0;
		for (AbstractDocument doc : _types.values()) {
			filter[i] = doc.getExtension();
			i++;
		}
		return filter;
	}
	
	public String [] getDescriptionFilter() {
		String []filter = new String[_types.values().size()];
		int i = 0;
		for (AbstractDocument doc : _types.values()) {
			filter[i] = doc.getFileDescription();
			i++;
		}
		return filter;
	}
}
